<template>
  <div class="detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="110px"
    >
      <div class="form-data">
        <el-form-item label="轮播图名称" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="轮播图名称"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="轮播图" prop="image">
          <image-item
            ref="imageItem"
            v-model="postForm.image"
            placeholder="轮播图"
            style="width: 100%"
            :limit="1"
            save-dir-name="banner"
          />
        </el-form-item>
        <el-form-item label="所属轮播位" prop="pos_id">
          <el-select
            v-model.number="postForm.pos_id"
            placeholder="所属轮播位"
            style="width: 100%"
            @change="changePosID"
          >
            <el-option v-for="item in bannerPosOptions" :key="item.id" :value="item.id" :label="item.title" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属文章" prop="article_id">
          <el-select
            v-model.number="postForm.article_id"
            placeholder="所属文章"
            style="width: 100%"
          >
            <el-option v-for="item in articleOptions" :key="item.id" :value="item.id" :label="item.title" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model.number="postForm.sort"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model.number="postForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import TnUploadImageItem from '@/components/TNUploadImageItem'
import { getBannerPosAllTitle } from '@/api/banner-pos'
import { getBannerByID, getBannerCountByPosID, addBanner, editBanner } from '@/api/banner'

const fields = {
  title: '轮播图名称',
  image: '轮播图'
}

const validateRequire = (rule, value, callback) => {
  if (!value || value === '' || value.trim() === '') {
    const errMsg = fields[rule.field] + '为必填项'
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

export default {
  name: 'BannerDetail',
  components: { Sticky, 'image-item': TnUploadImageItem },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isEdit: false,
      loading: false,
      bannerPosOptions: [],
      articleOptions: [{ id: 0, title: '' }],
      postForm: {
        title: '',
        image: '',
        pos_id: '',
        article_id: 0,
        sort: 1,
        status: 1
      },
      rules: {
        title: [
          { required: true, message: '轮播图名称不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        image: [
          { required: true, message: '轮播图不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        pos_id: [
          { required: true, message: '所属轮播位不能为空' },
          { type: 'number', message: '所属轮播位值格式不正确' }
        ],
        article_id: [
          { required: true, message: '所属文章不能为空' },
          { type: 'number', message: '所属文章值格式不正确' }
        ],
        sort: [
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序值格式不正确' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // 判断规则是否通过验证
          if (valid) {
            const banner = Object.assign({}, this.postForm)
            // console.log(menu)
            if (!this.isEdit) {
              addBanner(banner).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              banner.id = this.id
              editBanner(banner).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
    },
    getBannerByID() {
      if (this.id !== 0) {
        getBannerByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            this.changePosID(0)
            return
          }
          const {
            title,
            image,
            pos_id,
            article_id,
            sort,
            status
          } = response.data
          this.postForm = {
            title,
            image,
            pos_id,
            article_id,
            sort,
            status
          }
          this.isEdit = true
        }).catch(() => {
          this.isEdit = false
          this.toDefault()
        })
      } else {
        this.isEdit = false
        this.changePosID(0)
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.loading = false
    },
    getAllBannerPos() {
      getBannerPosAllTitle().then(response => {
        const { data } = response
        this.bannerPosOptions = data
        this.getBannerByID()
      })
    },
    changePosID(value) {
      getBannerCountByPosID(value).then(response => {
        const { count } = response
        this.postForm.sort = count + 1
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
